import React, { useState, useEffect } from 'react';
import { isEmpty } from '@/utils/common';
import styles from './NumberPicker.less';
// import { Toast, Modal } from 'antd-mobile';

export default function (props: any) {

  const [num, setNum] = useState(props.value || props.min || 0);

  const hasValue = (val: number) => (!!val || val === 0 || val === 1);

  const handleNumChange = (type:string, e?: any) => {
    let newNum = num;
    switch (type) {
      case 'sub': newNum--; break;
      case 'add': newNum++; break;
      case 'input': {
        e.target.value = e.target.value.replace(/[^\d]/g, '');
        if (e.target.value < props.min || isEmpty(e.target.value)) newNum = 0;
        else if (hasValue(props.max) && num > props.max) newNum = props.max;
        else newNum = e.target.value;
      }
      default: break;
    }
    if (props.canDelete && newNum < 1) {
      // Modal.confirm({
      //   title: '溫馨提示',
      //   content: '確認從購物車刪除嗎？',
      //   yes: () =>
      //     new Promise(resolve => {
      //       // Message.info({ showIcon: true, content: 'yes一秒后关闭' });
      //       // setTimeout(resolve, 1000);
      //     }),
      //   no: () => {
      //     console.log('no');
      //   },
      // });
    } else {
      newNum = newNum < 1 ? 0 : newNum;
      changeNum(newNum);
    }
    // props.callBackNum && props.callBackNum(newNum)
    e.stopPropagation();
  }

  const changeNum = (newNum:any) => {
    props.onChange && props.onChange(Number(newNum), props.attr);
    setNum(Number(newNum));
  }

  useEffect(() => {
    if (!isEmpty(props.value)) {
      let val = props.value;
      if (hasValue(props.max) && props.value > props.max) {
        val = props.max
      }
      setNum(val);
    }
    // console.log(props)
  }, [props])

  return <div className={`${styles.num_picker} ${props.className || ''}`}>
    <button
      type="button"
      className={styles.sub}
      disabled={num <= props.min}
      onClick={(e:any) => { handleNumChange('sub', e) }}
    >-</button>
    <input
      type="text"
      readOnly
      className={`${styles.num} ${props.hideNumber ? styles.hideNumber : ''}`}
      value={num}
      maxLength={3}
      onChange={(e) => { handleNumChange('input', e.target.value) }}
    />
    <button
      type="button"
      className={styles.add}
      disabled={hasValue(props.max) && num >= props.max}
      onClick={e => { handleNumChange('add', e) }}
    >+</button>
  </div>
}